<template>
  <div class="mg_coin_buy" :style="{'padding-bottom': paddingBottom + 'px'}">
    <div class="top-header border-bottom fixed-top">
      <div class="top-back">
        <a href="javascript:history.go(-1)"></a>
      </div>
      <h2 class="f36 ">确认订单</h2>
    </div>
    <div class="detail-main mt-97 pb-200">
      <div class="detail-bt border-bottom px-30 py-15 bg-fff ">
        <div class="detail-left fl">
          <div class="ware-titl f32 color-000">{{detail.title}}</div>
          <div class="ware-price f36 color-m1">￥{{detail.price}}</div>
          <div class="ware-client f26 color-666" v-show="detail.operatorName">{{detail.operatorName}}/{{detail.gameServerName}}</div>
        </div>
        <div class="stock">
          <span class=" color-666 f26">库存：{{detail.stockTotal}}件</span>
        </div>
      </div>
      <div class="detail-tutorial f32 border-bottom bg-f8 px-30 mb-20 " @click="popupVisible=true">
        <div class="hrgames-cfi f26 color-666 fl">
          <i class="firm mr-30 ">担保交易</i>
        </div>
        <a href="javascript:void(0)" class="sharembgs"></a>
      </div>
      <div class="mobilegames-mun bg-fff px-30 border-bottom border-top ">
        <div class="mobun-lf fl f30">购买件数</div>
        <div class="mobun-rg fr f30">
          <span class="list">
            <em>
              <a class="ch_redu" :class="{'ch_redu_hov': Number(coinClass.unitNum) <= 1,
                    'ch_redu': Number(coinClass.unitNum) > 1}" @click="unitNumSubtract"></a>
            </em>
            <com-input inputClass="char-fabu f30" :class="{'large-input': Number(coinClass.unitNum) > 9999}" defaultValue="1" :minValue="1" :maxValue="Number(detail.stockTotal) === 0 ? 1 : Number(detail.stockTotal)" v-model="coinClass.unitNum"></com-input>
            <em>
              <a :class="{'ch_add': Number(coinClass.unitNum) < Number(detail.stockTotal),
                   'ch_add_hov': Number(coinClass.unitNum) >= Number(detail.stockTotal)}" @click="unitNumAdd"></a>
            </em>
          </span>
        </div>
      </div>
      <div class="f24" v-if="showHint && !coinClass.unitNum" style="color: #be8600; line-height: .6rem; background-color: #fffdf4; padding-left: .3rem">
        请输入购买件数
      </div>
      <div class="mb-20"></div>
      <div class="mobilegames-mun border-top">
        <ul>
          <li class="px-30 border-bottom bg-fff color-000">
            <div class="mobun-lf fl f30">收货角色</div>
            <div class="mobun-cn fr f30">
              <input class="input-qq f30 color-000" type="text" maxlength="30" v-model="coinClass.roleName" placeholder="请输入收货角色名">
            </div>
          </li>
          <li class="px-30 border-bottom prompt" v-if="showHint && coinClass.roleName.length === 0">
            <div class="f24">请输入收货角色名</div>
          </li>
          <li class="px-30 border-bottom bg-fff color-000">
            <div class="mobun-lf fl f30">我的手机号</div>
            <div class="mobun-cn fr f30">
              <com-input inputClass="input-qq f30 color-000" :maxlength="11" inputPlaceholder="请输入手机号码" @writing="writing.phone=true" v-model="coinClass.phone"></com-input>
            </div>
          </li>
          <li class="px-30 border-bottom prompt" v-if="(showHint || writing.phone) && !telTrue">
            <div class="f24">请输入正确的手机号</div>
          </li>
          <li class="px-30 border-bottom bg-fff color-000">
            <div class="mobun-lf fl f30">我的QQ号</div>
            <div class="mobun-cn fr f30">
              <com-input inputClass="input-qq f30 color-000" inputPlaceholder="请输入QQ号" :maxlength="11" @writing="writing.qq=true" v-model="coinClass.qq"></com-input>
            </div>
          </li>
          <li class="px-30 border-bottom prompt" v-if="(showHint || writing.qq) && (coinClass.qq.length < 5 || coinClass.qq.length > 11)">
            <div class="f24">请输入正确的QQ号码</div>
          </li>
        </ul>
      </div>
      <div class="fixed-bottom border-top" ref="commitEle">
        <div class="goodslist-btn px-30 py-30 bg-fff">
          <a class="total f32 color-000 fl" href="#">合计
            <em class="color-m1 f37 ml-10">￥
              <i class="fontarial f40">{{totalPrice}}</i>
            </em>
          </a>
          <a class="suborder f36 bg-f54 color-fff fr text-center" @click="commitOrder">提交订单</a>
        </div>
      </div>
    </div>
    <mt-popup v-model="popupVisible" position="bottom">
      <!--服务保障-->
      <div class="sv-guarantee border-top bg-fff " style="width: 100%" @touchmove.prevent>
        <div class="scgtee-titl f32 color-666 border-bottom">
          <a class="close mr-30" @click="popupVisible=false"></a>服务保障
        </div>
        <div class="scgtee-demo px-30 border-bottom">
          <div class="sgde-lf fl">
            <i class="bao"></i>
          </div>
          <div class="sgde-tn">
            <div class="tn-til f28 color-000">担保交易</div>
            <div class="tn-txt f28 color-666 mt-10">卖家选择【担保交易】模式，需由客服联系卖家才能发货。</div>
          </div>
        </div>
        <div class="mt-80 bg-m1 f36 color-fff text-center sgde-btn" @click="popupVisible=false">朕知道了</div>
      </div>
    </mt-popup>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import ComInput from './coin_component/input.vue'

export default {
  components: {
    ComInput,
  },
  data() {
    return {
      detail: {}, // 商品详情
      popupVisible: false, // 是否显示服务信息
      account: {}, // 用户信息
      showHint: false, // 判空处理
      params: this.$route.params,
      query: this.$route.query,
      onLine: false, // 是否在发送提交订单接口
      coinClass: {
        roleName: '',
        phone: '',
        qq: '',
        unitNum: '1'
      },
      paddingBottom: 0,
      writing: {
        phone: false,
        qq: false,
      }
    }
  },
  created() {
    this.coinClass.phone = this.$getAccountInfo().mobilePhone || ''
    this.$indicator.open({
      spinnerType: 'fading-circle'
    })
  },
  computed: {
    /* 总价格 */
    totalPrice() {
      if (this.detail.price) {
        return (Number(this.coinClass.unitNum) * Number(this.detail.price)).toFixed(2)
      } else {
        return 0
      }
    },
    telTrue() {
      if (!(/^1[34578]\d{9}$/.test(this.coinClass.phone))) {
        return false;
      }
      return true
    }
  },
  mounted() {
    this.init()
    this.paddingBottom = this.$refs['commitEle'].offsetHeight
  },
  /* 页面销毁前 关闭该关闭的 停止该停止的 */
  beforeDestroy() {
    this.$indicator.close() // 关闭加载中提示
  },
  methods: {
    /* 增加件数 */
    unitNumAdd() {
      let newNum = (Number(this.coinClass.unitNum) + 1).toString()
      // 针对双十二活动做的判断
      if (this.$route.query.key === 'activity') {
        this.coinClass.unitNum = 1
        return false
      };
      if (newNum.length > 15 || Number(newNum) > this.detail.stockTotal)
        return
      this.coinClass.unitNum = newNum
    },
    /* 减少件数 */
    unitNumSubtract() {
      let newNum = Number(this.coinClass.unitNum) - 1
      if (newNum < 1) return
      this.coinClass.unitNum = newNum.toString()
    },
    /* 提交订单 */
    commitOrder() {
      if (this.onLine) return
      let coin = this.coinClass
      let ok = true
      /* 填写信息校验 */
      this.showHint = true
      for (let key in coin) { // 判空处理
        if (!coin[key].length)
          return
      }
      if (coin.phone.length !== 11 || coin.qq.length < 5 || coin.qq.length > 11) return // 长度判断
      if (!this.telTrue) return // 手机号码校验
      if (Number(this.totalPrice) >= 1000000) {
        this.$toast('购买价格不能大于等于 1000000')
        return
      } // 购买价格限制11位
      this.onLine = true
      this.$indicator.open()

      this.$http.post(this.$CONSTANTS.APIMGCoin + "order/gamemoney", {
        "bizOfferId": this.params.goodsId,
        "buyerPhone": coin.phone,
        "buyerQQ": coin.qq,
        goodsCount: coin.unitNum,
        "gameMoneyModel": {
          "gameRoleName": coin.roleName
        }
      }).then(({ data }) => {
        if (data.success) {
          this.mobileOrderPay(data.data).then(() => {
            this.onLine = false
            this.$indicator.close()
          })
        } else {
          this.$toast(data.responseStatus.message)
          this.onLine = false
          this.$indicator.close()
        }
      })
      return
      this.$http.post('/api/mobile-order-service/rs/order/currency/createsycurrencyorder', {
        buyType: 3,
        buyerPhone: coin.phone,
        buyerQq: coin.qq,
        buyerRoleName: coin.roleName,
        goodsId: this.params.goodsId,
        goodsType: 3,
        orderSource: 1,
        num: coin.unitNum
      }).then(({ data: res }) => {
        if (res.success) {
          let orderId = res.orderId
          let returnUrl = location.protocol + '//' + location.hostname + '/vue/buyerCenter/buyerMobCoinOrder/' + orderId
          this.$http.get('/api/mobile-order-service/rs/payment/mypay', { params: { orderId, returnUrl } }).then(res => {
            window.location.href = res.data.url
          }).then(() => {
            this.$indicator.close()
          })
        } else {
          this.$indicator.close()
          this.onLine = false
          this.$toast(res.responseStatus.message)
        }
      })
    },
    // 手游合并项目后 专属手游账号支付接口
    mobileOrderPay(orderId) {
      return this.$http.post(this.$CONSTANTS.APIMGCoin + "pay/orderPay", { orderId, sourceChannel: 2 }).then(({ data }) => {
        if (data.success) {
          location.href = 'https://mypay.5173.com/PaymentWap/PayExternalV2.aspx?' + data.data.payUrl
        } else {
          this.$toast(data.responseStatus.message)
        }
        return
      })
    },
    /* 获取页面必要初始信息 */
    init() {
      Promise.all([
        this.$http.post(this.$CONSTANTS.APIMGCoin + 'goods/getGoodsDetail', {
          bizOfferId: this.params.goodsId
        }).then(({ data }) => {
          if (data.success) {
            this.detail = data.data
          } else {
            this.$toast(data.responseStatus.message)
          }
          this.$indicator.close()
        }),
      ]).then(() => {
        this.$nextTick(() => {
          this.$indicator.close()
        })
      })
    },
    ...mapActions({
      getCoinDetail: 'MOBILE_GAME/SELL_COIN_GOODS_DETAIL'
    })
  }
}
</script>

<style>
.mg_coin_buy .mint-popup-bottom {
  width: 100%;
}

.mg002
  .mg_coin_buy
  .mobilegames-mun
  .mobun-rg
  span.list
  .char-fabu.large-input {
  width: 2rem;
}
</style>
